#!/usr/bin/env python
#
# Copyright 2007 Doug Hellmann.
#
"""Utility functions.

"""

__version__ = "$Id: utils.py 120 2008-05-26 21:02:22Z doug.hellmann $"

# Import system modules
import datetime
from itertools import *
import logging

from django.db import connection

# Import local modules


# Module
logger = logging.getLogger('docket.utils')


def months_in_year(year):
    """Return a sequence of datetime.date instances for the months
    in a given year.
    """
    return [ datetime.date(year, m, 1)
             for m in range(1, 13)
             ]

def query_to_dicts(query_string, *query_args):
    """Run a simple query and produce a generator
    that returns the results as a bunch of dictionaries
    with keys for the column values selected.
    """
    #logger.debug('query_to_dicts(%s, %s)', query_string, query_args)
    cursor = connection.cursor()
    cursor.execute(query_string, query_args)
    col_names = [desc[0].lower().replace(' ', '_')
                 for desc in cursor.description]
    while True:
        row = cursor.fetchone()
        if row is None:
            break
        row_dict = dict(izip(col_names, row))
        yield row_dict
    return

